package com.zhulin.android.edoctor.net;

/*
 * Copyright 2011 meiyitian
 * Blog  :http://www.cnblogs.com/meiyitian
 * Email :haoqqemail@qq.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import com.zhulin.android.edoctor.net.exception.RequestException;


import android.util.Log;
import android.widget.SimpleAdapter;

/**
 * 
 * 异步HTTPPOST请求
 * 
 * 线程的终止工作交给线程池，当activity停止的时候，设置回调函数为false ，就不会执行回调方法。
 * 
 * @author zxy
 * 
 */
public class AsyncHttpPost extends BaseRequest {
	private static final long serialVersionUID = 2L;
	DefaultHttpClient httpClient;
	//List<RequestParameter> parameter = null;
	Map<String, String> parameter=null;
	public AsyncHttpPost(ParseHandler handler, String url,Map<String, String> hashMap,
			RequestResultCallback requestCallback) {
		this.handler = handler;
		this.url = url;
		//this.parameter = parameter;
		this.parameter=hashMap;
		this.requestCallback = requestCallback;
		if (httpClient == null)
			httpClient = new DefaultHttpClient();
	}

	@Override
	public void run() {
		try {
			request = new HttpPost(url);
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url);
			//request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
			//request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,readTimeout);
			if(parameter!=null&&parameter.size()>0){
//				List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
//				for(RequestParameter p : parameter){
//					list.add(new BasicNameValuePair(p.getName(),p.getValue()));
//				}
//				((HttpPost)request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8) );
				
				JSONObject jsonObject=new JSONObject();
				
				Iterator<Entry<String, String>> strings= parameter.entrySet().iterator();
				while(strings.hasNext()){
					Entry<String,String> entry= strings.next();
					try {
						jsonObject.put(entry.getKey(), entry.getValue());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
//				for(RequestParameter p:parameter){
//					try {
//						jsonObject.put(p.getName(), p.getValue());
//					} catch (JSONException e) {
//						e.printStackTrace();
//					}
//				}
				StringEntity stringEntity=new StringEntity(jsonObject.toString(),"UTF-8");
				((HttpPost)request).setEntity(stringEntity);
			}
			HttpResponse response = httpClient.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				ByteArrayOutputStream content = new ByteArrayOutputStream();
				response.getEntity().writeTo(content);
				String ret = new String(content.toByteArray()).trim();
				//content.close();
				Object Object = null;

				try{
					if(AsyncHttpPost.this.handler !=null){
						Object = AsyncHttpPost.this.handler.handle(content);

						if( AsyncHttpPost.this.requestCallback != null&&Object !=null){
							AsyncHttpPost.this.requestCallback.onSuccess(Object);
							return ;
						}
						if(Object == null||"".equals(Object.toString())){
							RequestException exception = new RequestException(RequestException.IO_EXCEPTION,"数据读取异常");
							AsyncHttpPost.this.requestCallback.onFail(exception);
						}
					}else{
						AsyncHttpPost.this.requestCallback.onSuccess(content);
					}
				}finally{
					content.close();
				}
			} else {
				RequestException exception = new RequestException(
						RequestException.IO_EXCEPTION, "响应码异常,响应码："
								+ statusCode);
				AsyncHttpPost.this.requestCallback.onFail(exception);
			}

			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  finished !");
		}catch(java.lang.IllegalArgumentException e){
			RequestException exception = new RequestException(
					RequestException.IO_EXCEPTION, "连接错误");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			Log.d(AsyncHttpGet.class.getName(),
					"AsyncHttpPost  request to url :" + url + "  onFail  "
							+ e.getMessage());
		}  catch (org.apache.http.conn.ConnectTimeoutException e) {
			RequestException exception = new RequestException(
					RequestException.SOCKET_TIMEOUT_EXCEPTION, "连接超时");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  onFail  "
							+ e.getMessage());
		} catch (java.net.SocketTimeoutException e) {
			RequestException exception = new RequestException(
					RequestException.SOCKET_TIMEOUT_EXCEPTION, "读取超时");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  onFail  "
							+ e.getMessage());
		} catch (UnsupportedEncodingException e) {
			RequestException exception = new RequestException(
					RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "编码错误");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  "
							+ e.getMessage());
		} catch (org.apache.http.conn.HttpHostConnectException e) {
			RequestException exception = new RequestException(
					RequestException.CONNECT_EXCEPTION, "连接错误");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  "
							+ e.getMessage());
		} catch (ClientProtocolException e) {
			RequestException exception = new RequestException(
					RequestException.CLIENT_PROTOL_EXCEPTION, "客户端协议异常");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			e.printStackTrace();
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  ClientProtocolException "
							+ e.getMessage());
		} catch (IOException e) {
			RequestException exception = new RequestException(
					RequestException.IO_EXCEPTION, "数据读取异常");
			AsyncHttpPost.this.requestCallback.onFail(exception);
			e.printStackTrace();
			Log.d(AsyncHttpPost.class.getName(),
					"AsyncHttpGet  request to url :" + url + "  IOException  "
							+ e.getMessage());
		} finally {
			//request.
		}
		super.run();
	}
}
